import React, {Component} from 'react'
import T from 'prop-types'

import {Icon} from 'antd'

import './index.less'

import WeaSplitLine from "../wea-split-line"

class WeaScrollPagination extends Component {
    constructor(props) {
        super(props)
        this.timeout = null
        this.startTime = new Date()
        this.DataStatus = {
            loading: <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@iqit7c`} type="loading">&nbsp;&nbsp;&nbsp;&nbsp;加载中，请稍后！</Icon>,
            more: <span className="icon-blog-drop-down" style={{cursor:"pointer"}} onClick={this.fetchData}>&nbsp;点击加载更多！</span>,
            full: '没有更多内容！'
        }
        this.state = {
            className: props.className,
            showScroll: props.showScroll,
            height: props.height && props.height < 0 ? 0 : props.height,
            innerHeight: 'auto',
            isScrollRender: true, //是否滚动触发渲染
            isInited: true,//是否初始化
            isScrolled: false,//是否已滚动
            status: props.hasData ? this.DataStatus.more : this.DataStatus.full//是否有数据
        }
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.isReset) {//切换数据源滚动置顶，防止底部无限请求数据
            this.scrollTop()
        }

        let {height, innerHeight, isInited, isScrollRender, showScroll, className} = this.state,
            isHeightChange = false//是否高度变更

        if (nextProps.hasData === true) {//存在数据，加载更多
            this.setState({status: this.DataStatus.more})
        } else if (nextProps.hasData === false) {//不存在数据，数据已满
            this.setState({status: this.DataStatus.full})
        }

        if (nextProps.className != className) {
            this.setState({className: nextProps.className})
        }

        if (nextProps.showScroll != showScroll) {
            this.setState({showScroll: nextProps.showScroll})
        }

        if (nextProps.height != height) {
            isHeightChange = true
            this.throttleFunction(//高度变更节流
                () => {
                    this.setState({height: nextProps.height})
                    if (innerHeight != "auto") {
                        this.setState({innerHeight: nextProps.height + 100})
                    }
                }, 167, 300)()
        } else {
            isHeightChange = false
        }

        if (!isHeightChange) {
            if (isInited) {
                this.checkScroll()
                this.setState({isInited: false, isScrollRender: false})
            } else {
                if (isScrollRender) {
                    this.checkScroll()
                }
            }
        }
    }

    checkScroll = () => {
        if (!this.state.isScrolled) {//非滚动状态，检测是否需要添加滚动条
            let dom = document.getElementsByClassName('wea-sp-content')[0],
                {height, innerHeight} = this.state,
                {scrollHeight} = dom

            if (scrollHeight <= height) {//手动添加滚动条
                this.setState({isScrolled: false, innerHeight: height + 100})
            } else {//不需要滚动，设置自滚动，打开滚动状态
                this.setState({isScrolled: true, innerHeight: 'auto'})
            }
        }
    }

    resetScroll = () => {
        if (!this.state.isScrolled) {//非滚动状态，重置滚动
            this.setState({innerHeight: 'auto'})
        }
    }

    scrollTop = (height) => {
        let dom = document.getElementsByClassName('wea-sp-content')[0]
        dom.scrollTop = height
    }

    fetchData = () => {
        this.resetScroll()
        this.setState({status: this.DataStatus.loading},//请求数据之前，设置加载状态
            () => {
                // anruo test loading
                setTimeout(
                    () => {
                        this.props.fetchData()
                    }, 0
                )
            }
        )
    }

    throttleFunction = (method, delay, time) => {
        let timeout = this.timeout, startTime = this.startTime
        return () => {
            let context = this,
                args = arguments,
                curTime = new Date()
            clearTimeout(timeout)
            if (curTime - startTime >= time) {
                method.apply(context, args)
                this.startTime = curTime
            } else {
                this.timeout = setTimeout(method, delay)
            }
        }
    }

    onScroll = (event) => {
        const dom = event.currentTarget
        this.throttleFunction(//滚动事件节流
            () => {
                const {status} = this.state
                if (status == this.DataStatus.more) {
                    const {scrollTop, clientHeight, scrollHeight} = dom
                    if (scrollTop + clientHeight == scrollHeight) {
                        this.fetchData()
                    }
                }
            }, 167, 300)()
    }

    render() {
        let {status, height, innerHeight, className, showScroll} = this.state,
            {showTip} = this.props

        return (
            <div className={'wea-scroll-pagination ' + (className ? className : '')}>
                <div className='wea-sp-content' onScroll={this.onScroll} style={{
                    height: height,
                    width: (showScroll ? "100%" : "120%"),
                    paddingRight: (showScroll ? "1%" : "20%")
                }}>
                    <div style={{height: innerHeight}}>
                        {this.props.children}
                    </div>
                </div>
                <div className="wea-sp-tip">
                    {status}
                </div>
                {/*<WeaSplitLine style={{marginTop: "16px", display: (showTip ? "block" : "none")}}>*/}
                    {/*{status}*/}
                {/*</WeaSplitLine>*/}
            </div>
        )
    }
}

WeaScrollPagination.propTypes = {
    fetchData: T.func.isRequired,//数据加载函数，参数:'init'、'more'
    hasData: T.boolean,//有数据、无数据
    height: T.number.isRequired,//滚动区间高度
    className: T.string,//容器类
}

WeaScrollPagination.defaultProps = {
    className: ""
}

export default WeaScrollPagination

/*
 *** 滚动分页组件：无限滚动加载数据 ***
 > 高度事件节流
 > 滚动事件节流
 > 滚动触发前后监听
 > 数据加载前后监听
 > 数据加载自动识别滚动（空数据，数据不够高时可触发滚动）
 > 滚动条隐藏
 > 数据自动加载
 */
